package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @FileName IndexController
 * @Description
 * @Author msh
 * @date 2025-10-22
 **/
@Controller
public class IndexController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        //TODO 1、查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categories();

        //默认前缀：prefix: classpath:/templates/
        //默认后缀：suffix: .html
        //视图解析器进行拼串：classpath:/templates/ + return值 + .html
        model.addAttribute("categories", categoryEntities);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        System.out.println("调用了查询所有分类数据，并缓存到redis");
        Map<String, List<Catalog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        //1、获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redissonClient.getLock("my-Lock");
        //2、加锁
//        lock.lock();//阻塞式等待 默认加的锁的过期时间都是30s
        // 1、锁的自动续期，如果业务超长，运行期间自动给所续上新的30s。不用担心业务时间长,锁自动过期被删掉
        // 2、加锁业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁默认也会在30s以后自动删除
        lock.lock(10, TimeUnit.SECONDS);//设置ttl后,不会自动续期  确保自动解锁时间一定要大于业务执行时间
        //问题：在锁时间到了以后不会自动续期
        //1、如果传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时就是我们指定的时间
        //2、如果未指定锁的超时时间，就使用30*1000【lockWatchdogTimeout看门狗默认时间】
        //    只要占锁成功，会启动一个定时任务【重新给锁设置过期时间，新的过期时间就是看门狗的过期时间】
        //    internalLockLeaseTime【看门狗时间】 / 3L , 10s
        //最佳实战：
        // 1)lock.lock(30, TimeUnit.SECONDS);省去了整个续期操作。
        try {
            System.out.println("加锁成功,执行业务" + Thread.currentThread().getId());
//            Thread.sleep(30000);
        } catch (Exception e) {

        } finally {
            //3、解锁
            System.out.println("释放锁" + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    //保证一定能读到最新数据，修改期间，写锁是排他锁，读锁是共享锁
    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.writeLock();
        try {
            // 1、改数据加写锁，读数据加读锁
            rLock.lock();
            System.out.println("写锁加锁成功" + Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writeValue", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
            System.out.println("写锁释放成功" + Thread.currentThread().getId());
        }
        return s;
    }
    @GetMapping("/read")
    @ResponseBody
    public String readValue() {
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        //加读锁
        RLock rLock = lock.readLock();
        rLock.lock();
        System.out.println("读锁加锁成功" + Thread.currentThread().getId());
        String s = "";
        try {
            s = stringRedisTemplate.opsForValue().get("writeValue");
            Thread.sleep(30000);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
            System.out.println("读锁释放成功" + Thread.currentThread().getId());
        }
        return s;
    }

    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
//        park.trySetPermits(10)//设置信号量为10
//        park.acquire();//获取一个信号，获取一个值
        boolean b = park.tryAcquire();
        if(b){
            //执行业务
        }else{
            return "error";
        }
        return "ok: " + b;
    }
    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();//释放一个信号，释放一个值
        return "ok";
    }

    /**
     *  放假锁门
     *  所有的班人全都走完了，才能锁门
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);//设置计数为5
        door.await();//等待闭锁完成
        return "放假了";
    }
    @GetMapping("/gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") Long id) {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();//计数减1
        return id + "班的人都走完了……";
    }

}
